package server.service.impl;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.dao.FrmRequestLogDao;
import server.model.entity.FrmRequestLog;
import server.model.entity.Users;
import server.service.LogService;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Service
public class LogServiceImpl implements LogService {
    @Autowired
    private FrmRequestLogDao requestLogDao;

    @Override
    public void LoginLog(HttpServletRequest request, FrmRequestLog.Status status) {
        String ret = (String) SecurityUtils.getSubject().getSession().getAttribute("ret");
        if (status.equals(FrmRequestLog.Status.YES)) {
            Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
            FrmRequestLog sysLog = new FrmRequestLog();
            sysLog.setApiName("登录");
            sysLog.setAcceptJson(String.valueOf(users.getId()));
            sysLog.setIp(request.getHeader("X-real-ip"));
            sysLog.setBackJson("成功");
            sysLog.setStatus(status);
            Enumeration er = request.getHeaderNames();
            StringBuilder herder = new StringBuilder();
            while (er.hasMoreElements()) {
                String name = (String) er.nextElement();
                String value = request.getHeader(name);
                herder.append("  " + name + "=" + value);
            }
            sysLog.setHeaders(herder.toString());
            requestLogDao.save(sysLog);
        } else {
            FrmRequestLog sysLog = new FrmRequestLog();
            sysLog.setApiName("登录");
            sysLog.setAcceptJson(ret);
            sysLog.setIp(request.getHeader("X-real-ip"));
            sysLog.setBackJson("失败");
            sysLog.setStatus(status);
            Enumeration er = request.getHeaderNames();
            StringBuilder herder = new StringBuilder();
            while (er.hasMoreElements()) {
                String name = (String) er.nextElement();
                String value = request.getHeader(name);
                herder.append("  " + name + "=" + value);
            }
            sysLog.setHeaders(herder.toString());
            requestLogDao.save(sysLog);
        }
    }

    @Override
    public void logSave(FrmRequestLog requestLog) {
        requestLogDao.save(requestLog);
    }
}
